package com.hammer.m3u8downloader;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hammer.m3u8downloader.adapter.M3U8DownloadListAdapter;
import com.hammer.m3u8downloader.entity.M3U8DownloadItemEntity;
import com.hammer.m3u8downloader.util.LocalM3U8Manager;
import com.hammer.m3u8downloader.widget.InputDialog;
import com.hammer.m3u8downloader.widget.MenuDialog;
import com.hammer.m3u8downloader.widget.SnackDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.OnDeleteTaskListener;
import jaygoo.library.m3u8downloader.OnM3U8DownloadListener;
import jaygoo.library.m3u8downloader.bean.M3U8Task;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private M3U8DownloadListAdapter adapter;
    private List<M3U8DownloadItemEntity> downloadItemEntityList = new ArrayList<>();
    private SnackDialog snackDialog;
    private M3U8Service.M3U8Binder m3U8Binder;
    private boolean bindResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        Intent intent = new Intent(this, M3U8Service.class);/** 绑定服务 */
        bindResult = bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void initView() {
        snackDialog = new SnackDialog(this);
        listView = findViewById(R.id.lv_download);
        adapter = new M3U8DownloadListAdapter(this, R.layout.item_m3u8_download, listView, downloadItemEntityList);
        listView.setAdapter(adapter);
        adapter.setOnItemClickListener((position, itemEntity) -> showMenuDialog(itemEntity));
        findViewById(R.id.fab).setOnClickListener(view -> showInputDialog());
        findViewById(R.id.iv_manager).setOnClickListener(view -> startActivity(new Intent(MainActivity.this, LocalM3U8Activity.class)));
    }


    private void updateTaskList(List<M3U8DownloadItemEntity> tasks) {
        downloadItemEntityList.clear();
        downloadItemEntityList.addAll(tasks);
        adapter.notifyDataSetChanged();
    }

    private void addTask(String taskName, String taskUrl) {
        if (bindResult) {
            if (serviceConnection != null) {
                unbindService(serviceConnection);
            }
        }
        Intent intent = new Intent(this, M3U8Service.class);/** 绑定服务 */
        intent.putExtra("taskName", taskName);
        intent.putExtra("taskUrl", taskUrl);
        bindResult = bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            m3U8Binder = (M3U8Service.M3U8Binder) service;
            m3U8Binder.getM3U8Service().setOnM3U8DownloadListener(onM3U8DownloadListener);
            m3U8Binder.getM3U8Service().setOnTaskListChangedListener(downloadItemEntityList -> {
                updateTaskList(downloadItemEntityList);
            });
            Log.e("info", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("info", "service disconnected");
            /*  ToolsUtil.showToasty(context,"onServiceDisconnected");*/
        }

        @Override
        public void onBindingDied(ComponentName name) {
            Log.e("info", "service onBindingDied");
            /*  ToolsUtil.showToasty(context,"onBindingDied");*/
        }

        @Override
        public void onNullBinding(ComponentName name) {
            Log.e("info", "onNullBinding");
            /* ToolsUtil.showToasty(context,"onNullBinding");*/
        }
    };
    private OnM3U8DownloadListener onM3U8DownloadListener = new OnM3U8DownloadListener() {
        @Override
        public void onDownloadItem(M3U8Task task, long itemFileSize, final int totalTs, final int curTs) {
            super.onDownloadItem(task, itemFileSize, totalTs, curTs);
            //下载切片监听，非UI线程
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        if (adapter.isShowing(position)) {
                            adapter.getViewHolder(position).info.setText("正在下载：" + curTs + " -> " + totalTs);
                        }
                    }
                });
            }
        }

        @Override
        public void onDownloadSuccess(M3U8Task task) {
            super.onDownloadSuccess(task);
            //下载成功
            Log.e("info", "下载完成: path-> " + task.getM3U8().getM3u8FilePath() + " size-> " + task.getM3U8().getFormatFileSize());
            //removeSuccessTask(task.getUrl());
            if (downloadItemEntityList.size() > 0) {
                M3U8Downloader.getInstance().download(downloadItemEntityList.get(0).getTaskUrl());
            }
        }

        @Override
        public void onDownloadPending(M3U8Task task) {
            super.onDownloadPending(task);
            //加入队列，任务挂起
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        if (adapter.isShowing(position)) {
                            adapter.getViewHolder(position).progress.setIndeterminate(true);
                            adapter.getViewHolder(position).info.setText("任务排队，等待下载");
                            adapter.getViewHolder(position).speed.setText("0 K/s");
                        }
                    }
                });
            }
        }

        @Override
        public void onDownloadPause(final M3U8Task task) {
            super.onDownloadPause(task);
            //任务暂停
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        adapter.getViewHolder(position).progress.setIndeterminate(false);
                        adapter.getViewHolder(position).progress.setProgress((int) (task.getProgress() * 100));
                        adapter.getViewHolder(position).info.setText("任务暂停...");
                        adapter.getViewHolder(position).speed.setText("0 K/s");
                    }
                });
            }
        }

        @Override
        public void onDownloadProgress(final M3U8Task task) {
            super.onDownloadProgress(task);
            //下载进度，非UI线程
            Log.e("info", "正在下载: " + task.getProgress() * 100 + "%");
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        adapter.getViewHolder(position).progress.setIndeterminate(false);
                        adapter.getViewHolder(position).progress.setProgress((int) (task.getProgress() * 100));
                        adapter.getViewHolder(position).speed.setText(task.getFormatSpeed());
                    }
                });
            }
        }

        @Override
        public void onDownloadPrepare(final M3U8Task task) {
            super.onDownloadPrepare(task);
            //准备下载
            Log.e("info", "准备下载: " + task.getUrl());
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        adapter.getViewHolder(position).progress.setIndeterminate(true);
                        adapter.getViewHolder(position).info.setText("准备下载中...");
                        adapter.getViewHolder(position).speed.setText(task.getFormatSpeed());
                    }
                });
            }
        }

        @Override
        public void onDownloadError(final M3U8Task task, final Throwable errorMsg) {
            super.onDownloadError(task, errorMsg);
            //下载错误，非UI线程
            Log.e("info", "下载错误: " + errorMsg.toString());
            final int position = getTaskPosition(task.getUrl());
            if (position != -1) {
                runOnUiThread(() -> {
                    if (adapter.isShowing(position)) {
                        adapter.getViewHolder(position).progress.setIndeterminate(false);
                        adapter.getViewHolder(position).progress.setProgress((int) (task.getProgress() * 100));
                        adapter.getViewHolder(position).speed.setText(task.getFormatSpeed());
                        adapter.getViewHolder(position).info.setText(String.format("出现错误：%s", errorMsg.toString()));
                    }
                });
            }
        }
    };

    private void removeSuccessTask(String url) {
        for (int i = 0; i < downloadItemEntityList.size(); i++) {
            if (downloadItemEntityList.get(i).getTaskUrl().equals(url)) {
                downloadItemEntityList.remove(i);
                adapter.notifyDataSetChanged();
                break;
            }
        }
    }

    private int getTaskPosition(String url) {
        int position = -1;
        for (int i = 0; i < downloadItemEntityList.size(); i++) {
            if (downloadItemEntityList.get(i).getTaskUrl().equals(url)) {
                position = i;
                break;
            }
        }
        return position;
    }

    private void showInputDialog() {
        new InputDialog(MainActivity.this)
                .setDialogTitle("添加下载任务")
                .setDialogHint("输入M3U8下载地址")
                .setPositiveButton("确定", view -> {

                })
                .setNegativeButton("取消", view -> {

                })
                .setOnSubmitListener(text -> {
                    if (text.startsWith("http")) {
                        addTask(text, text);
                        return true;
                    } else {
                        Toast.makeText(MainActivity.this, "链接格式不正确", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                })
                .show();
    }


    private void showMenuDialog(final M3U8DownloadItemEntity entity) {
        new MenuDialog(this)
                .setMenuTitle("选择操作方式")
                .addMenuItem(Arrays.asList("暂停任务", "继续任务", "删除任务"))
                .setCallBack((dialogInterface, i) -> {
                    switch (i) {
                        case 0:
                            M3U8Downloader.getInstance().pause(entity.getTaskUrl());
                            break;
                        case 1:
                            M3U8Downloader.getInstance().download(entity.getTaskUrl());
                            break;
                        case 2:
                            new AlertDialog.Builder(MainActivity.this, R.style.MyAlertDialogStyle)
                                    .setTitle("提示")
                                    .setMessage("是否确认删除当前任务：" + entity.getTaskName())
                                    .setPositiveButton("彻底删除", (dialogInterface1, i1) -> {
                                        snackDialog.setTitle("删除任务").setSubTitle("正在删除").show();
                                        deleteTask(entity.getTaskUrl());
                                    })
                                    .setNegativeButton("保留缓存", (dialogInterface12, i12) -> {
                                        M3U8Downloader.getInstance().cancel(entity.getTaskUrl());
                                        LocalM3U8Manager.getInstance(MainActivity.this).deleteTask(entity.getTaskUrl());
                                        showWarningDialog("已删除下载记录，下次下载相同任务可以断点续传");

                                    })
                                    .setNeutralButton("取消", (dialogInterface13, i13) -> {

                                    })
                                    .show();
                            break;
                    }
                })
                .show();
    }


    private void deleteTask(final String url) {
        M3U8Downloader.getInstance().cancelAndDelete(url, new OnDeleteTaskListener() {
            @Override
            public void onStart() {
                runOnUiThread(() -> snackDialog.setSubTitle("开始删除..."));
            }

            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    LocalM3U8Manager.getInstance(MainActivity.this).deleteTask(url);
                    showWarningDialog("删除成功");
                    snackDialog.dismiss();
                });

            }

            @Override
            public void onFail() {
                runOnUiThread(() -> {
                    showWarningDialog("删除失败，请重试");
                    snackDialog.dismiss();
                });

            }

            @Override
            public void onError(final Throwable errorMsg) {
                runOnUiThread(() -> {
                    showWarningDialog("删除错误：" + errorMsg.toString());
                    snackDialog.dismiss();
                });

            }
        });
    }


    private void showWarningDialog(final String text) {
        new AlertDialog.Builder(MainActivity.this, R.style.MyAlertDialogStyle).setTitle("提示").setMessage(text).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*    handler.removeCallbacks(runnable);*/
        if (bindResult) {
            if (serviceConnection != null) {
                unbindService(serviceConnection);
            }
        }
    }
}
